#include <glog/logging.h>
#include <QFile>
#include <QDir>
#include <QCoreApplication>
#include <QProcess>
#include <QDataStream>

#include "constant.h"
#include "update/updater.h"
#include "manager/mqtt_manager.h"

Updater::Updater(char *archive, int len)
{
    m_archive = archive;
    m_len = len;
}

void Updater::update() {
    int len = m_len - UPDATE_CHECKSUM_LEN;
    LOG(INFO) << "Updater | update archive size" << len;
    if (m_archive != NULL && len > 0) {
        LOG(INFO) << "Updater | run | write update archive";
        QFile file(UPDATE_ARCHIVE_FILE);
        file.open(QIODevice::WriteOnly);
        QDataStream out(&file);
        for (int i = 0; i < len; ++i) {
            out << (unsigned char)*(m_archive + i);
        }
        file.close();
        untar_archive_file();
        MqttManager::getInstance()->send_update_result("ok");
        invoke_external_updater();
    }
}

void Updater::untar_archive_file() {
    LOG(INFO) << "Updater | untar_archive_file";
    QDir directory(UPDATE_ARCHIVE_DIR);
    if (directory.exists()) {
        directory.rmdir(UPDATE_ARCHIVE_DIR);
    }
    directory.mkdir(UPDATE_ARCHIVE_DIR);
    system(QString("tar -zxvf %1 -C %2").arg(UPDATE_ARCHIVE_FILE,
                                             UPDATE_ARCHIVE_DIR).toLatin1().data());
    system(QString("chmod 777 %1").arg(UPDATER_PATH).toLatin1().data());
}

void Updater::invoke_external_updater() {
    LOG(INFO) << "Updater | invoke_external_updater";
    system(QString("echo 'nvidia' | sudo -S %1 &").arg(UPDATER_PATH).toLatin1().data());
    LOG(INFO) << "Updater | invoke_external_updater | finish";
    QCoreApplication::exit(0);
}
